package com.genexususa.eo.google.connection;

import com.genexususa.eo.google.data.*;
import com.google.api.ads.adwords.axis.v201409.cm.*;
import com.google.api.ads.adwords.axis.v201409.cm.Image;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.imageio.ImageIO;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;

public class AdsManager {

    private static final int PAGE_SIZE = 5000;
    private String _clientId;

    public void SetClientId(String clientId) {
        this._clientId = clientId;
    }

    public String GetClientId() {
        return _clientId;
    }

    public void Finalize() {

        SessionController sc = SessionController.getInstance();
        sc.RemoveSession(_clientId);
    }

    private MediaSize getMediaSizeFromString(String mediaSizeString) {
        if (mediaSizeString.equalsIgnoreCase("S")) {
            return MediaSize.SHRUNKEN;
        }
        if (mediaSizeString.equalsIgnoreCase("P")) {
            return MediaSize.PREVIEW;
        }
        if (mediaSizeString.equalsIgnoreCase("V")) {
            return MediaSize.VIDEO_THUMBNAIL;
        }
        return MediaSize.FULL;
    }

    private Image parseImage(Node n) throws IOException {
        NodeList children = n.getChildNodes();
        if (children.getLength() > 0) {
            Image image = new Image();
            for (int j = 0; j < children.getLength(); j++) {
                /*if (children.item(j).getNodeName().equalsIgnoreCase("Dimensions")) {
                    NodeList dimensionsChildren = children.item(j).getChildNodes();
                    ArrayList<Media_Size_DimensionsMapEntry> dimensionList = new ArrayList<Media_Size_DimensionsMapEntry>();
                    for (int k=0; k<dimensionsChildren.getLength(); k++) {
                        if (dimensionsChildren.item(k).getNodeName().equalsIgnoreCase("Dimension")) {
                            NodeList dimensionChildren = dimensionsChildren.item(k).getChildNodes();
                            Media_Size_DimensionsMapEntry dimension = new Media_Size_DimensionsMapEntry();
                            dimension.setValue(new Dimensions());
                            for (int l=0; l<dimensionChildren.getLength(); l++) {
                                if (dimensionChildren.item(l).getNodeName().equalsIgnoreCase("Key")) {
                                    dimension.setKey(this.getMediaSizeFromString(dimensionChildren.item(l).getTextContent()));
                                }
                                if (dimensionChildren.item(l).getNodeName().equalsIgnoreCase("Width")) {
                                    dimension.getValue().setWidth(Integer.valueOf(dimensionChildren.item(l).getTextContent()));
                                }
                                if (dimensionChildren.item(l).getNodeName().equalsIgnoreCase("Height")) {
                                    dimension.getValue().setHeight(Integer.valueOf(dimensionChildren.item(l).getTextContent()));
                                }
                            }
                            dimensionList.add(dimension);
                        }
                    }
                    Media_Size_DimensionsMapEntry[] dimensions = new Media_Size_DimensionsMapEntry[]{};
                    image.setDimensions(dimensionList.toArray(dimensions));
                }*/
                /*if (children.item(j).getNodeName().equalsIgnoreCase("Urls")) {
                    NodeList urlsChildren = children.item(j).getChildNodes();
                    ArrayList<Media_Size_StringMapEntry> urlList = new ArrayList<Media_Size_StringMapEntry>();
                    for (int k=0; k<urlsChildren.getLength(); k++) {
                        if (urlsChildren.item(k).getNodeName().equalsIgnoreCase("Url")) {
                            NodeList urlChildren = urlsChildren.item(k).getChildNodes();
                            Media_Size_StringMapEntry url = new Media_Size_StringMapEntry();
                            for (int l=0; l<urlChildren.getLength(); l++) {
                                if (urlChildren.item(l).getNodeName().equalsIgnoreCase("Key")) {
                                    url.setKey(this.getMediaSizeFromString(urlChildren.item(l).getTextContent()));
                                }
                                if (urlChildren.item(l).getNodeName().equalsIgnoreCase("Value")) {
                                    url.setValue(urlChildren.item(l).getTextContent());
                                }
                            }
                            urlList.add(url);
                        }
                    }
                    Media_Size_StringMapEntry[] urls = new Media_Size_StringMapEntry[]{};
                    image.setUrls(urlList.toArray(urls));
                }*/
                if (children.item(j).getNodeName().equalsIgnoreCase("Name")) {
                    image.setName(children.item(j).getTextContent());
                }
                if (children.item(j).getNodeName().equalsIgnoreCase("DataLocation")) {
                    File file = new File(children.item(j).getTextContent());
                    BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    int i = 0;
                    while ((i = inputStream.read()) != -1) {
                        outputStream.write(i);
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    image.setData(outputStream.toByteArray());


                    ArrayList<Media_Size_DimensionsMapEntry> dimensionList = new ArrayList<Media_Size_DimensionsMapEntry>();
                    Media_Size_DimensionsMapEntry dimension = new Media_Size_DimensionsMapEntry();
                    dimension.setKey(MediaSize.FULL);
                    Dimensions dim = new Dimensions();
                    BufferedImage buff = ImageIO.read(file);
                    dim.setWidth(buff.getWidth());
                    dim.setHeight(buff.getHeight());
                    dimensionList.add(dimension);
                    Media_Size_DimensionsMapEntry[] dimensions = new Media_Size_DimensionsMapEntry[]{};
                    image.setDimensions(dimensionList.toArray(dimensions));
                }
            }
            return image;
        }
        return null;
    }

    private void parseAdNode(Node node, GA_ResultItem gaAd, AdGroupAd adGroupAd, boolean create) {
        if (node.getNodeName().equalsIgnoreCase("CampaignID")) {
            gaAd.CampaignId = Long.parseLong(node.getTextContent());
        }

        if (node.getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
            gaAd.SubCampaignGxId = Long.parseLong(node.getTextContent());
        }

        if (node.getNodeName().equalsIgnoreCase("AdGroupId")) {
            gaAd.AdGroupId = Long.parseLong(node.getTextContent());
            adGroupAd.setAdGroupId(Long.parseLong(node.getTextContent()));
        }

        if (node.getNodeName().equalsIgnoreCase("AdGroupGxId")) {
            gaAd.AdGroupGxId = Long.parseLong(node.getTextContent());
        }

        if (!create) {
            if (node.getNodeName().equalsIgnoreCase("AdId")) {
                adGroupAd.getAd().setId(Long.parseLong(node.getTextContent()));
            }
        }

        if (node.getNodeName().equalsIgnoreCase("AdGxId")) {
            gaAd.AdGxId = Long.parseLong(node.getTextContent());
        }

        if (node.getNodeName().equalsIgnoreCase("AdStatus")) {
            if (node.getTextContent().equalsIgnoreCase("E")) {
                adGroupAd.setStatus(AdGroupAdStatus.ENABLED);
            } else if (node.getTextContent().equalsIgnoreCase("P")) {
                adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
            } else if (node.getTextContent().equalsIgnoreCase("D")) {
                adGroupAd.setStatus(AdGroupAdStatus.DISABLED);
            }
        }

        if (node.getNodeName().equalsIgnoreCase("Url")) {
            adGroupAd.getAd().setUrl(node.getTextContent());
        }

        if (node.getNodeName().equalsIgnoreCase("DisplayUrl")) {
            adGroupAd.getAd().setDisplayUrl(node.getTextContent());
        }

        if (node.getNodeName().equalsIgnoreCase("DevicePreference")) {
            adGroupAd.getAd().setDevicePreference(Long.parseLong(node.getTextContent()));
        }
    }

    private GA_ResultItem parseAdImage(Node n, boolean create) throws IOException {
        NodeList children = n.getChildNodes();
        GA_ResultItem gaAdImage = new GA_ResultItem();

        if (children.getLength() > 0) {

            AdGroupAd adGroupAd = new AdGroupAd();
            ImageAd imageAd = new ImageAd();
            adGroupAd.setAd(imageAd);

            for (int j = 0; j < children.getLength(); j++) {
                this.parseAdNode(children.item(j), gaAdImage, adGroupAd, create);

                if (children.item(j).getNodeName().equalsIgnoreCase("Name")) {
                    imageAd.setName(children.item(j).getTextContent());
                }

                if (create) {
                    if (children.item(j).getNodeName().equalsIgnoreCase("Image")) {
                        Image image = this.parseImage(children.item(j));
                        if (image != null) {
                            imageAd.setImage(image);
                        }
                    }
                    if (children.item(j).getNodeName().equalsIgnoreCase("AdToCopyImageFrom")) {
                        if (Long.valueOf(children.item(j).getTextContent()) != 0) {
                            imageAd.setAdToCopyImageFrom(Long.valueOf(children.item(j).getTextContent()));
                        }
                    }
                }
            }

            gaAdImage.ImageAd = adGroupAd;

            return gaAdImage;
        }
        return null;
    }

    private GA_ResultItem parseAdMobileImage(Node n, boolean create) throws IOException {
        NodeList children = n.getChildNodes();
        GA_ResultItem gaAdMobileImage = new GA_ResultItem();

        if (children.getLength() > 0) {

            AdGroupAd adGroupAd = new AdGroupAd();
            MobileImageAd mobileImageAd = new MobileImageAd();
            adGroupAd.setAd(mobileImageAd);

            for (int j = 0; j < children.getLength(); j++) {
                this.parseAdNode(children.item(j), gaAdMobileImage, adGroupAd, create);

                if (children.item(j).getNodeName().equalsIgnoreCase("MarkupLanguages")) {
                    NodeList markupLanguageNodes = children.item(j).getChildNodes();
                    MarkupLanguageType[] markupLanguageTypes = new MarkupLanguageType[markupLanguageNodes.getLength()];
                    mobileImageAd.setMarkupLanguages(markupLanguageTypes);
                    for (int k=0; k<markupLanguageNodes.getLength(); k++) {
                        if (markupLanguageNodes.item(k).getNodeName().equalsIgnoreCase("MarkupLanguage")) {
                            markupLanguageTypes[k] = Util.markupLanguageFromString(markupLanguageNodes.item(k).getTextContent());
                        }
                    }
                    mobileImageAd.setMarkupLanguages(markupLanguageTypes);
                }

                if (children.item(j).getNodeName().equalsIgnoreCase("MobileCarriers")) {
                    NodeList mobileCarrierNodes = children.item(j).getChildNodes();
                    String[] mobileCarriers = new String[mobileCarrierNodes.getLength()];
                    mobileImageAd.setMobileCarriers(mobileCarriers);
                    for (int k=0; k<mobileCarrierNodes.getLength(); k++) {
                        if (mobileCarrierNodes.item(k).getNodeName().equalsIgnoreCase("MobileCarrier")) {
                            mobileCarriers[k] = mobileCarrierNodes.item(k).getTextContent();
                        }
                    }
                    mobileImageAd.setMobileCarriers(mobileCarriers);
                }

                if (create) {
                    if (children.item(j).getNodeName().equalsIgnoreCase("Image")) {
                        Image image = this.parseImage(children.item(j));
                        if (image != null) {
                            mobileImageAd.setImage(image);
                        }
                    }
                }
            }

            gaAdMobileImage.MobileImageAd = adGroupAd;

            return gaAdMobileImage;
        }
        return null;
    }

    public String CreateAdText(String xml) {
        try {
            String result = "";
            // Get the instance of servicAdExtensionOverrideServicee's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());
            GA_Result res = new GA_Result();
            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr
                    = xpath.compile("//GA_AdText");
            Object adTextNodes = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList adTexts = (NodeList) adTextNodes;
            ArrayList<GA_ResultItem> textAds = new ArrayList<GA_ResultItem>();
            if (adTexts.getLength() > 0) {
                for (int i = 0; i < adTexts.getLength(); i++) { // For all GA_AdText Nodes
                    Node n = adTexts.item(i);
                    NodeList children = n.getChildNodes();
                    GA_ResultItem gaAdText = new GA_ResultItem();
                    if (children.getLength() > 0) {
                        AdGroupAd adGroupAd = new AdGroupAd();
                        TextAd textAd = new TextAd();
                        for (int j = 0; j < children.getLength(); j++) {
                            if (children.item(j).getNodeName().equalsIgnoreCase("CampaignID")) {
                                gaAdText.CampaignId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                gaAdText.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupId")) {
                                gaAdText.AdGroupId = Long.parseLong(children.item(j).getTextContent());
                                adGroupAd.setAdGroupId(Long.parseLong(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupGxId")) {
                                gaAdText.AdGroupGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGxId")) {
                                gaAdText.AdGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdStatus")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.DISABLED);
                                }
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Url")) {

                                textAd.setUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("DisplayUrl")) {

                                textAd.setDisplayUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Headline")) {
                                textAd.setHeadline(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Dsc1")) {
                                textAd.setDescription1(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Dsc2")) {
                                textAd.setDescription2(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("DevicePreference")) {
                                textAd.setDevicePreference(Long.parseLong(children.item(j).getTextContent()));
                            }
                        }

                        adGroupAd.setAd(textAd);

                        gaAdText.TextAd = adGroupAd;

                        textAds.add(gaAdText);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();

                for (GA_ResultItem adText : textAds) {

                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(adText.TextAd);
                    operation.setOperator(Operator.ADD);

                    ops.add(operation);

                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

                AdGroupAdOperation[] operations = ops.toArray(opsArray);


                AdGroupAdReturnValue returnValue = adService.mutate(operations);

                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdText = new GA_ResultItem();

                    createAdText.AdGroupGxId = textAds.get(i).AdGroupGxId;
                    createAdText.AdGroupId = textAds.get(i).AdGroupId;
                    createAdText.AdGxId = textAds.get(i).AdGxId;
                    createAdText.CampaignId = textAds.get(i).CampaignId;
                    createAdText.SubCampaignGxId = textAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdText.AdId = 0L;
                        createAdText.HasError = true;


                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                        j++;

                        errors.Errors.add(err);

                        createAdText.Errors = errors;

                        created.add(createAdText);

                    } else {

                        createAdText.AdId = returnValue.getValue(i).getAd().getId();
                        createAdText.AdGroupId = returnValue.getValue(i).getAdGroupId();

                        created.add(createAdText);

                    }

                }


                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";
            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;
            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String CreateAdImage(String xml) {

        try {

            String result = "";

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());

            //GA_ResultCreateAdImage res = new GA_ResultCreateAdImage();

            GA_Result res = new GA_Result();


            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_AdImage");

            Object adImageNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList adImages = (NodeList) adImageNodes;

            ArrayList<GA_ResultItem> imageAds = new ArrayList<GA_ResultItem>();

            if (adImages.getLength() > 0) {


                for (int i = 0; i < adImages.getLength(); i++) { // For all GA_AdImage Nodes
                    GA_ResultItem gaAdImage = this.parseAdImage(adImages.item(i), true);
                    if (gaAdImage != null) {
                        imageAds.add(gaAdImage);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();

                for (GA_ResultItem adImage : imageAds) {

                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(adImage.ImageAd);
                    operation.setOperator(Operator.ADD);

                    ops.add(operation);

                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

                AdGroupAdOperation[] operations = ops.toArray(opsArray);


                AdGroupAdReturnValue returnValue = adService.mutate(operations);

                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdImage = new GA_ResultItem();

                    createAdImage.AdGroupGxId = imageAds.get(i).AdGroupGxId;
                    createAdImage.AdGroupId = imageAds.get(i).AdGroupId;
                    createAdImage.AdGxId = imageAds.get(i).AdGxId;
                    createAdImage.CampaignId = imageAds.get(i).CampaignId;
                    createAdImage.SubCampaignGxId = imageAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdImage.AdId = 0L;
                        createAdImage.HasError = true;


                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                        j++;

                        errors.Errors.add(err);

                        createAdImage.Errors = errors;

                        created.add(createAdImage);

                    } else {

                        createAdImage.AdId = returnValue.getValue(i).getAd().getId();
                        createAdImage.AdGroupId = returnValue.getValue(i).getAdGroupId();

                        created.add(createAdImage);

                    }

                }


                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {

            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String CreateAdMobileImage(String xml) {

        try {

            String result = "";

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());

            GA_Result res = new GA_Result();


            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_AdMobileImage");

            Object adMobileImageNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList adMobileImages = (NodeList) adMobileImageNodes;

            ArrayList<GA_ResultItem> mobileImageAds = new ArrayList<GA_ResultItem>();

            if (adMobileImages.getLength() > 0) {


                for (int i = 0; i < adMobileImages.getLength(); i++) { // For all GA_AdMobileImage Nodes
                    GA_ResultItem gaAdMobileImage = this.parseAdMobileImage(adMobileImages.item(i), true);
                    if (gaAdMobileImage != null) {
                        mobileImageAds.add(gaAdMobileImage);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();

                for (GA_ResultItem adMobileImage : mobileImageAds) {

                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(adMobileImage.MobileImageAd);
                    operation.setOperator(Operator.ADD);

                    ops.add(operation);

                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

                AdGroupAdOperation[] operations = ops.toArray(opsArray);


                AdGroupAdReturnValue returnValue = adService.mutate(operations);

                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdMobileImage = new GA_ResultItem();

                    createAdMobileImage.AdGroupGxId = mobileImageAds.get(i).AdGroupGxId;
                    createAdMobileImage.AdGroupId = mobileImageAds.get(i).AdGroupId;
                    createAdMobileImage.AdGxId = mobileImageAds.get(i).AdGxId;
                    createAdMobileImage.CampaignId = mobileImageAds.get(i).CampaignId;
                    createAdMobileImage.SubCampaignGxId = mobileImageAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdMobileImage.AdId = 0L;
                        createAdMobileImage.HasError = true;


                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                        j++;

                        errors.Errors.add(err);

                        createAdMobileImage.Errors = errors;

                        created.add(createAdMobileImage);

                    } else {

                        createAdMobileImage.AdId = returnValue.getValue(i).getAd().getId();
                        createAdMobileImage.AdGroupId = returnValue.getValue(i).getAdGroupId();

                        created.add(createAdMobileImage);

                    }

                }


                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {

            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String CreateMobileAd(String xml){
        try {
            String result = "";
            // Get the instance of servicAdExtensionOverrideServicee's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());
            GA_Result res = new GA_Result();

            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//GA_MobileAd");
            Object adMobileNodes = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList mobileAdsNodeList = (NodeList) adMobileNodes;

            ArrayList<GA_ResultItem> mobileAds = new ArrayList<GA_ResultItem>();

            if (mobileAdsNodeList.getLength() > 0) {
                for (int i = 0; i < mobileAdsNodeList.getLength(); i++) { // For all GA_AdMobile Nodes
                    Node n = mobileAdsNodeList.item(i);
                    NodeList children = n.getChildNodes();
                    GA_ResultItem gaAdMobile = new GA_ResultItem();

                    if (children.getLength() > 0) {
                        AdGroupAd adGroupAd = new AdGroupAd();
                        MobileAd mobileAd = new MobileAd();

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("CampaignID")) {
                                gaAdMobile.CampaignId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                gaAdMobile.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupId")) {
                                gaAdMobile.AdGroupId = Long.parseLong(children.item(j).getTextContent());
                                adGroupAd.setAdGroupId(Long.parseLong(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupGxId")) {
                                gaAdMobile.AdGroupGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGxId")) {
                                gaAdMobile.AdGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdStatus")) {

                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.DISABLED);
                                }
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Headline")) {
                                mobileAd.setHeadline(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Description")) {
                                mobileAd.setDescription(children.item(j).getTextContent());
                            }

                            mobileAd.setMobileCarriers(new String[]{"ALLCARRIERS"});

                            if (children.item(j).getNodeName().equalsIgnoreCase("PhoneNumber")){
                                mobileAd.setPhoneNumber(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("CountryCode")){
                                mobileAd.setCountryCode(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("BusinessName")){
                                mobileAd.setBusinessName(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("DisplayUrl")){
                                mobileAd.setDisplayUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("DestinationUrl")){
                                mobileAd.setUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("MarkupLanguages")){
                                NodeList languages = children.item(j).getChildNodes();
                                ArrayList<MarkupLanguageType> markupLanguages = new ArrayList<MarkupLanguageType>();
                                for (int h = 0; h < languages.getLength(); h++) {
                                    if (languages.item(h).getNodeName().equalsIgnoreCase("MarkupLanguage")){
                                        markupLanguages.add(MarkupLanguageType.fromString(languages.item(h).getTextContent()));
                                    }
                                }

                                MarkupLanguageType[] lt = new MarkupLanguageType[]{};
                                mobileAd.setMarkupLanguages(markupLanguages.toArray(lt));
                            }

                        }

                        adGroupAd.setAd(mobileAd);
                        gaAdMobile.MobileAd = adGroupAd;
                        mobileAds.add(gaAdMobile);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();
                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();
                for (GA_ResultItem mobileAd : mobileAds) {
                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(mobileAd.MobileAd);
                    operation.setOperator(Operator.ADD);
                    ops.add(operation);
                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};
                AdGroupAdOperation[] operations = ops.toArray(opsArray);
                AdGroupAdReturnValue returnValue = adService.mutate(operations);
                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdText = new GA_ResultItem();

                    createAdText.AdGroupGxId = mobileAds.get(i).AdGroupGxId;
                    createAdText.AdGroupId = mobileAds.get(i).AdGroupId;
                    createAdText.AdGxId = mobileAds.get(i).AdGxId;
                    createAdText.CampaignId = mobileAds.get(i).CampaignId;
                    createAdText.SubCampaignGxId = mobileAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdText.AdId = 0L;
                        createAdText.HasError = true;
                        ErrorsStruct errors = new ErrorsStruct();
                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();
                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();
                        j++;
                        errors.Errors.add(err);
                        createAdText.Errors = errors;
                        created.add(createAdText);

                    } else {

                        createAdText.AdId = returnValue.getValue(i).getAd().getId();
                        createAdText.AdGroupId = returnValue.getValue(i).getAdGroupId();
                        created.add(createAdText);
                    }
                }
                try {
                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringWriter sw = new StringWriter();
                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String UpdateMobileAd(String xml){
        try {
            String result = "";
            // Get the instance of servicAdExtensionOverrideServicee's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());
            GA_Result res = new GA_Result();

            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//GA_MobileAd");
            Object adMobileNodes = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList mobileAdsNodeList = (NodeList) adMobileNodes;

            ArrayList<GA_ResultItem> mobileAds = new ArrayList<GA_ResultItem>();

            if (mobileAdsNodeList.getLength() > 0) {
                for (int i = 0; i < mobileAdsNodeList.getLength(); i++) { // For all GA_AdMobile Nodes
                    Node n = mobileAdsNodeList.item(i);
                    NodeList children = n.getChildNodes();
                    GA_ResultItem gaAdMobile = new GA_ResultItem();

                    if (children.getLength() > 0) {
                        AdGroupAd adGroupAd = new AdGroupAd();
                        MobileAd mobileAd = new MobileAd();

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("CampaignID")) {
                                gaAdMobile.CampaignId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                gaAdMobile.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupId")) {
                                gaAdMobile.AdGroupId = Long.parseLong(children.item(j).getTextContent());
                                adGroupAd.setAdGroupId(Long.parseLong(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupGxId")) {
                                gaAdMobile.AdGroupGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGxId")) {
                                gaAdMobile.AdGxId= Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdStatus")) {

                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.DISABLED);
                                }
                            }
                        }

                        adGroupAd.setAd(mobileAd);
                        gaAdMobile.MobileAd = adGroupAd;
                        mobileAds.add(gaAdMobile);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();
                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();
                for (GA_ResultItem mobileAd : mobileAds) {
                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(mobileAd.MobileAd);
                    operation.setOperator(Operator.ADD);
                    ops.add(operation);
                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};
                AdGroupAdOperation[] operations = ops.toArray(opsArray);
                AdGroupAdReturnValue returnValue = adService.mutate(operations);
                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdText = new GA_ResultItem();

                    createAdText.AdGroupGxId = mobileAds.get(i).AdGroupGxId;
                    createAdText.AdGroupId = mobileAds.get(i).AdGroupId;
                    createAdText.AdGxId = mobileAds.get(i).AdGxId;
                    createAdText.CampaignId = mobileAds.get(i).CampaignId;
                    createAdText.SubCampaignGxId = mobileAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdText.AdId = 0L;
                        createAdText.HasError = true;
                        ErrorsStruct errors = new ErrorsStruct();
                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();
                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();
                        j++;
                        errors.Errors.add(err);
                        createAdText.Errors = errors;
                        created.add(createAdText);

                    } else {

                        createAdText.AdId = returnValue.getValue(i).getAd().getId();
                        createAdText.AdGroupId = returnValue.getValue(i).getAdGroupId();
                        created.add(createAdText);
                    }
                }
                try {
                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringWriter sw = new StringWriter();
                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String UpdateAdText(String xml) {

        try {

            String result = "";

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());

            //GA_ResultCreateAdText res = new GA_ResultCreateAdText();

            GA_Result res = new GA_Result();


            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_AdText");

            Object adTextNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList adTexts = (NodeList) adTextNodes;

            ArrayList<GA_ResultItem> textAds = new ArrayList<GA_ResultItem>();

            if (adTexts.getLength() > 0) {


                for (int i = 0; i < adTexts.getLength(); i++) { // For all GA_AdText Nodes

                    Node n = adTexts.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem gaAdText = new GA_ResultItem();

                    if (children.getLength() > 0) {

                        AdGroupAd adGroupAd = new AdGroupAd();

                        TextAd textAd = new TextAd();

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("CampaignID")) {
                                gaAdText.CampaignId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdId")) {
                                gaAdText.AdId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                gaAdText.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupId")) {
                                gaAdText.AdGroupId = Long.parseLong(children.item(j).getTextContent());
                                adGroupAd.setAdGroupId(Long.parseLong(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGroupGxId")) {
                                gaAdText.AdGroupGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdGxId")) {
                                gaAdText.AdGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdStatus")) {

                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adGroupAd.setStatus(AdGroupAdStatus.DISABLED);
                                }
                            }

                            /*if (children.item(j).getNodeName().equalsIgnoreCase("Url")){

                                textAd.setUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("DisplayUrl")){

                                textAd.setDisplayUrl(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Headline")){
                                textAd.setHeadline(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Dsc1")){
                                textAd.setDescription1(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Dsc2")){
                                textAd.setDescription2(children.item(j).getTextContent());
                            }    */
                        }


                        textAd.setId(gaAdText.AdId);

                        adGroupAd.setAd(textAd);

                        gaAdText.TextAd = adGroupAd;

                        textAds.add(gaAdText);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();

                for (GA_ResultItem adText : textAds) {

                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(adText.TextAd);
                    operation.setOperator(Operator.SET);

                    ops.add(operation);

                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

                AdGroupAdOperation[] operations = ops.toArray(opsArray);


                AdGroupAdReturnValue returnValue = adService.mutate(operations);

                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdText = new GA_ResultItem();

                    createAdText.AdGroupGxId = textAds.get(i).AdGroupGxId;
                    createAdText.AdGroupId = textAds.get(i).AdGroupId;
                    createAdText.AdGxId = textAds.get(i).AdGxId;
                    createAdText.CampaignId = textAds.get(i).CampaignId;
                    createAdText.SubCampaignGxId = textAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdText.AdId = 0L;
                        createAdText.HasError = true;


                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                        j++;

                        errors.Errors.add(err);

                        createAdText.Errors = errors;

                        created.add(createAdText);

                    } else {

                        createAdText.AdId = returnValue.getValue(i).getAd().getId();
                        createAdText.AdGroupId = returnValue.getValue(i).getAdGroupId();

                        created.add(createAdText);

                    }
                }


                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {

            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String UpdateAdImage(String xml) {

        try {

            String result = "";

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());

            //GA_ResultCreateAdImage res = new GA_ResultCreateAdImage();

            GA_Result res = new GA_Result();


            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_AdImage");

            Object adImageNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList adImages = (NodeList) adImageNodes;

            ArrayList<GA_ResultItem> imageAds = new ArrayList<GA_ResultItem>();

            if (adImages.getLength() > 0) {


                for (int i = 0; i < adImages.getLength(); i++) { // For all GA_AdImage Nodes
                    GA_ResultItem gaAdImage = this.parseAdImage(adImages.item(i), false);
                    if (gaAdImage != null) {
                        imageAds.add(gaAdImage);
                    }
                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<AdGroupAdOperation> ops = new ArrayList<AdGroupAdOperation>();

                for (GA_ResultItem adImage : imageAds) {

                    AdGroupAdOperation operation = new AdGroupAdOperation();
                    operation.setOperand(adImage.ImageAd);
                    operation.setOperator(Operator.SET);

                    ops.add(operation);

                }

                AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

                AdGroupAdOperation[] operations = ops.toArray(opsArray);


                AdGroupAdReturnValue returnValue = adService.mutate(operations);

                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createAdImage = new GA_ResultItem();

                    createAdImage.AdGroupGxId = imageAds.get(i).AdGroupGxId;
                    createAdImage.AdGroupId = imageAds.get(i).AdGroupId;
                    createAdImage.AdGxId = imageAds.get(i).AdGxId;
                    createAdImage.CampaignId = imageAds.get(i).CampaignId;
                    createAdImage.SubCampaignGxId = imageAds.get(i).SubCampaignGxId;

                    if (returnValue.getValue(i).getAd() == null) {

                        createAdImage.AdId = 0L;
                        createAdImage.HasError = true;


                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                        j++;

                        errors.Errors.add(err);

                        createAdImage.Errors = errors;

                        created.add(createAdImage);

                    } else {

                        createAdImage.AdId = returnValue.getValue(i).getAd().getId();
                        createAdImage.AdGroupId = returnValue.getValue(i).getAdGroupId();

                        created.add(createAdImage);

                    }
                }


                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }

            }


            return result;

        } catch (Exception exc) {

            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String DeleteAd(String adIds, String adGroupIds){


        try {

            String result = "";

            GA_Result res = new GA_Result();

            GA_ResultItem deleted = new GA_ResultItem();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(this.GetClientId());
            ArrayList<GA_ResultItem> deletedAds = new ArrayList<GA_ResultItem>();

            String[] adIdsArray = adIds.split(";");

            String[] adGroupIdsArray = adGroupIds.split(";");

            ArrayList<AdGroupAdOperation> deleteOperations = new ArrayList<AdGroupAdOperation>();


            for (int i = 0; i < adIdsArray.length; i++){

                GA_ResultItem deletedAd = new GA_ResultItem();
                // Create base class ad to avoid setting type specific fields.
                Ad ad = new Ad();
                ad.setId(Long.parseLong(adIdsArray[i].trim()));


                // Create ad group ad.
                AdGroupAd adGroupAd = new AdGroupAd();
                adGroupAd.setAdGroupId(Long.parseLong(adGroupIdsArray[i].trim()));
                adGroupAd.setAd(ad);

                // Create operations.
                AdGroupAdOperation operation = new AdGroupAdOperation();
                operation.setOperand(adGroupAd);
                operation.setOperator(Operator.REMOVE);

                deletedAd.AdId = Long.parseLong(adIdsArray[i]);
                deletedAd.AdGroupId = Long.parseLong(adGroupIdsArray[i].trim());
                deletedAds.add(deletedAd);

                deleteOperations.add(operation);


            }

            AdGroupAdOperation[] opsArray = new AdGroupAdOperation[]{};

            AdGroupAdOperation[] operations = deleteOperations.toArray(opsArray);


            ArrayList<GA_ResultItem> returnDeletedAds = new ArrayList<GA_ResultItem>();

            //AdGroupAdOperation[] operations = new AdGroupAdOperation[]{operation};

            AdGroupAdReturnValue returnValue = adService.mutate(operations);

            Thread.sleep(1000);

            int j = 0;

            for (int i = 0; i < returnValue.getValue().length; i++) {

                GA_ResultItem deleteAd = new GA_ResultItem();

                deleteAd.AdGroupId = deletedAds.get(i).AdGroupId;

                if (returnValue.getValue(i).getAd() == null) {

                    deleteAd.AdId = 0L;
                    deleteAd.HasError = true;


                    ErrorsStruct errors = new ErrorsStruct();

                    errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                    errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                    com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                    err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                    err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                    //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                    err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                    err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();

                    j++;

                    errors.Errors.add(err);

                    deleteAd.Errors = errors;

                    returnDeletedAds.add(deleteAd);

                } else {

                    deleteAd.AdId = returnValue.getValue(i).getAd().getId();
                    deleteAd.AdGroupId = returnValue.getValue(i).getAdGroupId();

                    returnDeletedAds.add(deleteAd);

                }

            }


            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = returnDeletedAds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }




            return result;



        } catch (Exception exc) {

            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public ArrayList<MobileAdReport> GetMobileAds(String clientId){
        ArrayList<MobileAdReport> result = new ArrayList<MobileAdReport>();
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();
        try {

            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(clientId);
            int offset = 0;
            // Create selector.
            Selector selector = new Selector();
            selector.setFields(new String[]{
                    "Id",
                    "Status",
                    "Url",
                    "DisplayUrl",
                    "MobileAdHeadline",
                    "MobileAdDescription",
                    "MobileAdMarkupLanguages",
                    "MobileAdMobileCarriers",
                    "MobileAdBusinessName",
                    "MobileAdCountryCode",
                    "MobileAdPhoneNumber"
            });
            selector.setOrdering(new OrderBy[]{new OrderBy("Id", SortOrder.ASCENDING)});
            selector.setPaging(new Paging(offset, PAGE_SIZE));
            // Create predicates.
            /*Predicate adGroupIdPredicate =
                    new Predicate("AdGroupId", PredicateOperator.IN, new String[]{adGroupId.toString()});*/
            // By default disabled ads aren't returned by the selector. To return them
            // include the DISABLED status in a predicate.
            Predicate statusPredicate =
                    new Predicate("Status", PredicateOperator.NOT_EQUALS,
                            new String[]{"DISABLED"});
            Predicate adTypePredicate =
                    new Predicate("AdType", PredicateOperator.EQUALS, new String[]{"MOBILE_AD"});
            selector.setPredicates(new Predicate[]{statusPredicate, adTypePredicate});
            AdGroupAdPage page = null;


            do {

                page = adService.get(selector);

                if (page.getEntries() != null) {
                    for (AdGroupAd adGroupAd : page.getEntries()) {
                        MobileAdReport mobileAdReport = new MobileAdReport();
                        if (adGroupAd.getAd() instanceof MobileAd) {
                            MobileAd mobileAd = (MobileAd)adGroupAd.getAd();

                            mobileAdReport.AdGroupId = adGroupAd.getAdGroupId();
                            mobileAdReport.Id = mobileAd.getId();
                            mobileAdReport.BusinessName = mobileAd.getBusinessName();
                            mobileAdReport.CountryCode = mobileAd.getCountryCode();
                            mobileAdReport.Description = mobileAd.getDescription();
                            mobileAdReport.DestinationUrl = mobileAd.getUrl();
                            mobileAdReport.DisplayUrl = mobileAd.getDisplayUrl();
                            mobileAdReport.Headline = mobileAd.getHeadline();
                            mobileAdReport.PhoneNumber = mobileAd.getPhoneNumber();

                            if (mobileAd.getMarkupLanguages().length > 0){
                                for (int i = 0; i < mobileAd.getMarkupLanguages().length; i++) {
                                    mobileAdReport.MarkupLanguages.add(mobileAd.getMarkupLanguages(i).getValue());
                                }
                            }

                            if (mobileAd.getMobileCarriers().length > 0){
                                for (int i = 0; i < mobileAd.getMobileCarriers().length; i++) {
                                    mobileAdReport.Carriers.add(mobileAd.getMobileCarriers(i));
                                }
                            }

                            result.add(mobileAdReport);

                        }


                    }
                }


                offset += PAGE_SIZE;
                selector.getPaging().setStartIndex(offset);

            } while (offset < page.getTotalNumEntries());
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }


        return result;


    }



    protected ArrayList<TextAdReport> GetTextAds(String clientId) {

        ArrayList<TextAdReport> result = new ArrayList<TextAdReport>();

        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(clientId);

            int offset = 0;

            // Create selector.
            Selector selector = new Selector();
            selector.setFields(new String[]{
                    "Description1",
                    "Description2",
                    "DevicePreference",
                    "DisplayUrl",
                    "Headline",
                    "Id",
                    "Status",
                    "Url"
            });
            selector.setOrdering(new OrderBy[]{new OrderBy("Id", SortOrder.ASCENDING)});
            selector.setPaging(new Paging(offset, PAGE_SIZE));

            // Create predicates.
        /*Predicate adGroupIdPredicate =
                new Predicate("AdGroupId", PredicateOperator.IN, new String[]{adGroupId.toString()});*/
            // By default disabled ads aren't returned by the selector. To return them
            // include the DISABLED status in a predicate.
            Predicate statusPredicate =
                    new Predicate("Status", PredicateOperator.NOT_EQUALS,
                            new String[]{"DISABLED"});
            Predicate adTypePredicate =
                    new Predicate("AdType", PredicateOperator.EQUALS, new String[]{"TEXT_AD"});
            selector.setPredicates(new Predicate[]{statusPredicate, adTypePredicate});
            AdGroupAdPage page = null;
            do {

                page = adService.get(selector);

                if (page.getEntries() != null) {
                    for (AdGroupAd adGroupAd : page.getEntries()) {
                        TextAdReport textAdReport = new TextAdReport();
                        if (adGroupAd.getAd() instanceof TextAd) {
                            TextAd textAd = (TextAd)adGroupAd.getAd();

                            textAdReport.AdGroupId = adGroupAd.getAdGroupId();
                            textAdReport.Description1 = textAd.getDescription1();
                            textAdReport.Description2 = textAd.getDescription2();
                            textAdReport.DevicePreference = textAd.getDevicePreference();
                            textAdReport.DisplayUrl = textAd.getDisplayUrl();
                            textAdReport.Headline = textAd.getHeadline();
                            textAdReport.Id = textAd.getId();
                            textAdReport.Url = textAd.getUrl();

                            if (adGroupAd.getStatus() == AdGroupAdStatus.ENABLED) {
                                textAdReport.Status = "E";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.PAUSED) {
                                textAdReport.Status = "P";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.DISABLED) {
                                textAdReport.Status = "D";
                            }

                            result.add(textAdReport);
                        }

                        /*System.out.println("Ad with id  \"" + adGroupAd.getAd().getId() + "\"" + " and type \""
                                + adGroupAd.getAd().getAdType() + "\" was found."); */
                    }
                }


                offset += PAGE_SIZE;
                selector.getPaging().setStartIndex(offset);

            } while (offset < page.getTotalNumEntries());
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }


        return result;

    }

    public ArrayList<ImageAdReport> GetImageAds(String clientId) {

        ArrayList<ImageAdReport> result = new ArrayList<ImageAdReport>();

        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();
        try {
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(clientId);

            int offset = 0;

            // Create selector.
            Selector selector = new Selector();
            selector.setFields(new String[]{
                    "DevicePreference",
                    "DisplayUrl",
                    "Id",
                    "ImageCreativeName",
                    "Status",
                    "Url"
            });
            selector.setOrdering(new OrderBy[]{new OrderBy("Id", SortOrder.ASCENDING)});
            selector.setPaging(new Paging(offset, PAGE_SIZE));

            // Create predicates.
        /*Predicate adGroupIdPredicate =
                new Predicate("AdGroupId", PredicateOperator.IN, new String[]{adGroupId.toString()});*/
            // By default disabled ads aren't returned by the selector. To return them
            // include the DISABLED status in a predicate.
            Predicate statusPredicate =
                    new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"DISABLED"});
            Predicate adTypePredicate =
                    new Predicate("AdType", PredicateOperator.EQUALS, new String[]{"IMAGE_AD"});
            selector.setPredicates(new Predicate[]{statusPredicate, adTypePredicate});
            AdGroupAdPage page = null;

            do {

                page = adService.get(selector);

                if (page.getEntries() != null) {
                    for (AdGroupAd adGroupAd : page.getEntries()) {
                        ImageAdReport imageAdReport = new ImageAdReport();
                        if (adGroupAd.getAd() instanceof ImageAd) {
                            ImageAd imageAd = (ImageAd)adGroupAd.getAd();

                            imageAdReport.AdGroupId = adGroupAd.getAdGroupId();
                            imageAdReport.DevicePreference = imageAd.getDevicePreference();
                            imageAdReport.DisplayUrl = imageAd.getDisplayUrl();
                            imageAdReport.Name = imageAd.getName();
                            imageAdReport.Id = imageAd.getId();
                            imageAdReport.Url = imageAd.getUrl();

                            if (adGroupAd.getStatus() == AdGroupAdStatus.ENABLED) {
                                imageAdReport.Status = "E";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.PAUSED) {
                                imageAdReport.Status = "P";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.DISABLED) {
                                imageAdReport.Status = "D";
                            }

                            result.add(imageAdReport);
                        }

                        /*System.out.println("Ad with id  \"" + adGroupAd.getAd().getId() + "\"" + " and type \""
                  + adGroupAd.getAd().getAdType() + "\" was found."); */
                    }
                }


                offset += PAGE_SIZE;
                selector.getPaging().setStartIndex(offset);

            } while (offset < page.getTotalNumEntries());
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }


        return result;

    }

    protected ArrayList<MobileImageAdReport> GetMobileImageAds(String clientId) {

        ArrayList<MobileImageAdReport> result = new ArrayList<MobileImageAdReport>();

        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();
        try {
            AdGroupAdServiceInterface adService = sf.GetAdGroupAdService(clientId);

            int offset = 0;

            // Create selector.
            Selector selector = new Selector();
            selector.setFields(new String[]{
                    "DevicePreference",
                    "DisplayUrl",
                    "Id",
                    "MobileImageAdMarkupLanguages",
                    "MobileImageAdMobileCarriers",
                    "Status",
                    "Url"
            });
            selector.setOrdering(new OrderBy[]{new OrderBy("Id", SortOrder.ASCENDING)});
            selector.setPaging(new Paging(offset, PAGE_SIZE));

            // Create predicates.
        /*Predicate adGroupIdPredicate =
                new Predicate("AdGroupId", PredicateOperator.IN, new String[]{adGroupId.toString()});*/
            // By default disabled ads aren't returned by the selector. To return them
            // include the DISABLED status in a predicate.
            Predicate statusPredicate =
                    new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"DISABLED"});
            Predicate adTypePredicate =
                    new Predicate("AdType", PredicateOperator.EQUALS, new String[]{"MOBILE_IMAGE_AD"});
            selector.setPredicates(new Predicate[]{statusPredicate, adTypePredicate});
            AdGroupAdPage page = null;

            do {

                page = adService.get(selector);

                if (page.getEntries() != null) {
                    for (AdGroupAd adGroupAd : page.getEntries()) {
                        MobileImageAdReport mobileImageAdReport = new MobileImageAdReport();
                        if (adGroupAd.getAd() instanceof MobileImageAd) {
                            MobileImageAd mobileImageAd = (MobileImageAd)adGroupAd.getAd();

                            mobileImageAdReport.AdGroupId = adGroupAd.getAdGroupId();
                            mobileImageAdReport.DevicePreference = mobileImageAd.getDevicePreference();
                            mobileImageAdReport.DisplayUrl = mobileImageAd.getDisplayUrl();
                            mobileImageAdReport.Id = mobileImageAd.getId();
                            mobileImageAdReport.Url = mobileImageAd.getUrl();

                            if (adGroupAd.getStatus() == AdGroupAdStatus.ENABLED) {
                                mobileImageAdReport.Status = "E";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.PAUSED) {
                                mobileImageAdReport.Status = "P";
                            } else if (adGroupAd.getStatus() == AdGroupAdStatus.DISABLED) {
                                mobileImageAdReport.Status = "D";
                            }

                            for (MarkupLanguageType markupLanguageType : mobileImageAd.getMarkupLanguages()) {
                                mobileImageAdReport.MarkupLanguages.add(Util.markupLanguageToString(markupLanguageType));
                            }

                            for (String mobileCarrier : mobileImageAd.getMobileCarriers()) {
                                mobileImageAdReport.MobileCarriers.add(mobileCarrier);
                            }

                            result.add(mobileImageAdReport);
                        }
                    }
                }


                offset += PAGE_SIZE;
                selector.getPaging().setStartIndex(offset);

            } while (offset < page.getTotalNumEntries());
        } catch (Exception exc) {
            exc.printStackTrace(System.out);
        }


        return result;

    }

}
